﻿using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace MapDisks
{
    class Program
    {
        static void Main(string[] args)
        {
            if(IsLocalLogon())
            {                
                return;  
            }
            Console.WriteLine("Domain logon");
            DirectoryEntry entry = new DirectoryEntry("");
            
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = string.Format("(&(objectClass=user)(samAccountName={0}))", Environment.UserName);
            searcher.SearchScope = SearchScope.Subtree;
            searcher.PropertiesToLoad.Add("memberOf");
            
            SearchResult result = searcher.FindOne();

            Dictionary<string, string> mappings = new Dictionary<string, string>();

            List<string> matchedGroups = new List<string>();

            foreach(string groupDN in result.Properties["memberOf"])
            {                
                AddGroupMappings(mappings, groupDN, matchedGroups);
            }

            foreach(KeyValuePair<string,string> item in mappings)
            {
                Console.WriteLine("Mapping {0} to {1}", item.Key, item.Value); 
                NETRESOURCE res = new NETRESOURCE();
                res.LocalName = item.Key + ":";
                res.RemoteName = item.Value;
                res.dwType=1;
                res.Provider = null;
                Native.WNetAddConnection2(res, null, null, 2);
            }
        }

        private static void AddGroupMappings(Dictionary<string, string> mappings, string groupDN, List<string> matchedGroups)
        {
            if(matchedGroups.Contains(groupDN))
            {
                return; 
            }

            matchedGroups.Add(groupDN);

            Console.WriteLine("Member of: {0}", groupDN);

            DirectoryEntry entry = new DirectoryEntry("LDAP://" + groupDN);
            foreach(string mapping in entry.Properties["mappedDisk"])
            {
                string[] data = mapping.Split(':');
                mappings[data[0]] = data[1];
            }

            foreach(string item in entry.Properties["memberOf"])
            {
                AddGroupMappings(mappings, item, matchedGroups); 
            }
        }

        private static bool IsLocalLogon()
        {
            return Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.CurrentCultureIgnoreCase);
        }
    }
}
